package com.c.yinyuezhushou.Service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.c.yinyuezhushou.MRetrofit.MusicItem;
import com.c.yinyuezhushou.MRetrofit.MyObserver;
import com.c.yinyuezhushou.MRetrofit.RetrofitService;
import com.c.yinyuezhushou.MRetrofit.getSongUrl;
import com.c.yinyuezhushou.MRetrofit.MyRetrofit;
import com.c.yinyuezhushou.MyApplication;
import com.c.yinyuezhushou.R;
import com.c.yinyuezhushou.Sql.MyDButil;
import com.c.yinyuezhushou.Ui.PlayerActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers;

import static android.os.PowerManager.PARTIAL_WAKE_LOCK;


public class MusicService extends Service {

    private MediaPlayer mMusicPlayer;

    private MyApplication myApplication;

    private MyDButil myDButil;

    private LocalBroadcastManager localBroadcastManager;
    private IntentFilter intentFilter;
    private MusicReceiver musicReceiver;


    private MusicItem musicItem;

    private List<MusicItem> musicItems;

    private int playtype=0;

    private WifiManager.WifiLock wifiLock;


    private List<MusicItem> lslist;

    private RemoteViews remoteViews;
    private RemoteViews remoteViews2;
    private Notification builder;

    public List<MusicItem> getLslist() {
        lslist = myDButil.getMusicItemTable("LsMusicItem");
        return lslist;
    }

    public void setMusicItems(List<MusicItem> musicItems) {
        this.musicItems = musicItems;
    }

    public void setPlaytype(int playtype) {
        this.playtype = playtype;
    }

    public int getPlaytype() {
        return playtype;
    }

    public List<MusicItem> getMusicItems() {
        return musicItems;
    }


    //0列表1随机2单曲循环

    public MusicItem getMusicItem() {
        return musicItem;
    }


    public void setSql(MusicItem musicItem){
        if (myDButil.isMusicItemTable(musicItem,"LsMusicItem")){
            myDButil.removeMusicItemTable(musicItem,"LsMusicItem");
        }
        myDButil.setMusicItemTable(musicItem,"LsMusicItem");
        lslist = myDButil.getMusicItemTable("LsMusicItem");
    }

    public MusicItem getSql(){
        musicItems = myDButil.getMusicItemTable("LsMusicItem");
        if (musicItems.size()==0){
            MusicItem musicItem = new MusicItem();
            musicItem.setImageurl("https://p2.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg?imageView=1&thumbnail=400z400&type=webp&quality=80");
            musicItem.setSong("星辰大海");
            musicItem.setSinger("黄霄雲");
            musicItem.setId(1811921555);
            return musicItem;
        }
        return musicItems.get(musicItems.size()-1);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        mMusicPlayer = new MediaPlayer();

        mMusicPlayer.setWakeMode (getApplicationContext(),PARTIAL_WAKE_LOCK);

        wifiLock = ((WifiManager) getApplicationContext().getSystemService(this.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

        wifiLock.acquire();

        myApplication = (MyApplication) getApplication();

        myDButil = myApplication.getMyDButil();

        musicItem = getSql();

        remoteViews();

        prepareToPlay1(musicItem);

    }

    class MusicReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("test1","sjjdd");
            switch (intent.getAction()){
                case "com.c.yueguangzhushou.play":
                    start();
                    break;
                case "com.c.yueguangzhushou.next":
                    next();
                    break;
                case "com.c.yueguangzhushou.back":
                    back();
                    break;
                case "com.c.yueguangzhushou.love":
                    if (myDButil.isMusicItemTable(musicItem,"LoveMusicItem")){
                        if (myDButil.removeMusicItemTable(musicItem,"LoveMusicItem")){
                            Toast.makeText(myApplication, "不爱了...", Toast.LENGTH_SHORT).show();
                            remoteViews2.setImageViewResource(R.id.nbm_image2,R.drawable.icon_love2_1);
                            remoteViews.setImageViewResource(R.id.nm_image2,R.drawable.icon_love2_1);
                            startForeground(1,builder);
                        }
                    }else {
                        if (myDButil.setMusicItemTable(musicItem,"LoveMusicItem")){
                            Toast.makeText(myApplication, "爱了爱了", Toast.LENGTH_SHORT).show();
                            remoteViews2.setImageViewResource(R.id.nbm_image2,R.drawable.icon_love1_1);
                            remoteViews.setImageViewResource(R.id.nm_image2,R.drawable.icon_love1_1);
                            startForeground(1,builder);
                        }
                    }
                    break;
            }
        }
    }


    public void remoteViews(){
        remoteViews = new RemoteViews(getPackageName(), R.layout.notification_big_music);
        remoteViews.setTextViewText(R.id.nm_text1,musicItem.getSong());
        remoteViews.setTextViewText(R.id.nm_text2,musicItem.getSinger());
        remoteViews2 = new RemoteViews(getPackageName(), R.layout.notification_music);
        remoteViews2.setTextViewText(R.id.nbm_text1,musicItem.getSong());
        remoteViews2.setTextViewText(R.id.nbm_text2,musicItem.getSinger());

        if (myDButil.isMusicItemTable(musicItem,"LoveMusicItem")){
            remoteViews2.setImageViewResource(R.id.nbm_image2,R.drawable.icon_love1_1);
            remoteViews.setImageViewResource(R.id.nm_image2,R.drawable.icon_love1_1);
        }else {
            remoteViews2.setImageViewResource(R.id.nbm_image2,R.drawable.icon_love2_1);
            remoteViews.setImageViewResource(R.id.nm_image2,R.drawable.icon_love2_1);
        }

        intentFilter = new IntentFilter();
        intentFilter.addAction("com.c.yueguangzhushou.play");
        intentFilter.addAction("com.c.yueguangzhushou.next");
        intentFilter.addAction("com.c.yueguangzhushou.back");
        intentFilter.addAction("com.c.yueguangzhushou.love");

        musicReceiver = new MusicReceiver();

        MusicService.this.registerReceiver(musicReceiver,intentFilter);

        Glide.with(this)
                .asBitmap()
                .load(musicItem.getImageurl())
                .apply(RequestOptions.bitmapTransform(new RoundedCorners(20)))
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        try {
                            remoteViews2.setImageViewBitmap(R.id.nbm_image1,resource);
                            remoteViews.setImageViewBitmap(R.id.nm_image1,resource);

                            PendingIntent pendingIntent1 = PendingIntent.getBroadcast(MusicService.this,1,new Intent("com.c.yueguangzhushou.play"),0);
                            PendingIntent pendingIntent2 = PendingIntent.getBroadcast(MusicService.this,2,new Intent("com.c.yueguangzhushou.next"),0);
                            PendingIntent pendingIntent3 = PendingIntent.getBroadcast(MusicService.this,3,new Intent("com.c.yueguangzhushou.back"),0);
                            PendingIntent pendingIntent4 = PendingIntent.getBroadcast(MusicService.this,4,new Intent("com.c.yueguangzhushou.love"),0);

                            remoteViews.setOnClickPendingIntent(R.id.nm_image2,pendingIntent4);
                            remoteViews.setOnClickPendingIntent(R.id.nm_image3,pendingIntent3);
                            remoteViews.setOnClickPendingIntent(R.id.nm_image4,pendingIntent1);
                            remoteViews.setOnClickPendingIntent(R.id.nm_image5,pendingIntent2);

                            remoteViews2.setOnClickPendingIntent(R.id.nbm_image2,pendingIntent4);
                            remoteViews2.setOnClickPendingIntent(R.id.nbm_image3,pendingIntent3);
                            remoteViews2.setOnClickPendingIntent(R.id.nbm_image4,pendingIntent1);
                            remoteViews2.setOnClickPendingIntent(R.id.nbm_image5,pendingIntent2);

                            NotificationCompat.BigPictureStyle inboxStyle = new NotificationCompat.BigPictureStyle();

                            Intent intent = new Intent(MusicService.this, PlayerActivity.class);
                            PendingIntent pendingIntent = PendingIntent.getActivity(MusicService.this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);

                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                                NotificationChannel notificationChannel = new NotificationChannel("1",
                                        "正在播放", NotificationManager.IMPORTANCE_DEFAULT);

                                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                                manager.createNotificationChannel(notificationChannel);
                            }

                            builder = new NotificationCompat.Builder(MusicService.this,"1")
                                    .setSmallIcon(R.mipmap.ic_launcher)
                                    .setContent(remoteViews2)
                                    .setCustomBigContentView(remoteViews)
                                    .setContentText(musicItem.getSong()+" - "+musicItem.getSinger())
                                    .setDefaults(Notification.DEFAULT_ALL)
                                    .setContentTitle("正在播放...")
                                    .setContentIntent(pendingIntent)
                                    .setStyle(inboxStyle)
                                    .setPriority(1000)
                                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                                    .build();

                            startForeground(1,builder);
                        }catch (Exception e){

                        }


                        addOnStateChangeListenerInner(new OnStateChangeListenr() {
                            @Override
                            public void onPlay(long time) {
                                remoteViews.setImageViewResource(R.id.nm_image4,R.drawable.icon_playing1_2);
                                remoteViews2.setImageViewResource(R.id.nbm_image4,R.drawable.icon_playing1_2);
                                setNofitication();
                            }

                            @Override
                            public void onPlayComplete() {
                                remoteViews.setImageViewResource(R.id.nm_image4,R.drawable.icon_playing1_1);
                                remoteViews2.setImageViewResource(R.id.nbm_image4,R.drawable.icon_playing1_1);
                                setNofitication();
                            }

                            @Override
                            public void onStateChange(boolean isplay, long nowtime) {
                                if (isplay){
                                    remoteViews.setImageViewResource(R.id.nm_image4,R.drawable.icon_playing1_2);
                                    remoteViews2.setImageViewResource(R.id.nbm_image4,R.drawable.icon_playing1_2);
                                }else {
                                    remoteViews.setImageViewResource(R.id.nm_image4,R.drawable.icon_playing1_1);
                                    remoteViews2.setImageViewResource(R.id.nbm_image4,R.drawable.icon_playing1_1);
                                }
                                setNofitication();
                            }

                            @Override
                            public void onSchedule(long nowtime) {

                            }

                            @Override
                            public void OnTimeVariety(long nowtime) {

                            }

                            @Override
                            public void loadfinised() {

                            }
                        });
                    }
                });
    }

    public void setNofitication(){
        remoteViews.setTextViewText(R.id.nm_text1,musicItem.getSong());
        remoteViews.setTextViewText(R.id.nm_text2,musicItem.getSinger());
        remoteViews2.setTextViewText(R.id.nbm_text1,musicItem.getSong());
        remoteViews2.setTextViewText(R.id.nbm_text2,musicItem.getSinger());
        Glide.with(MusicService.this)
                .asBitmap()
                .load(musicItem.getImageurl())
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        remoteViews2.setImageViewBitmap(R.id.nbm_image1,resource);
                        remoteViews.setImageViewBitmap(R.id.nm_image1,resource);
                        startForeground(1,builder);
                    }
                });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(musicReceiver);
        mMusicPlayer.release();
        mListenerList.clear();
        wifiLock.release();
    }



    public class MusicServiceIBinder extends Binder {

        public MusicService getMusicService(){
            return MusicService.this;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicServiceIBinder();
    }


    public void test(){
        Log.d("test1","uiueryhui");
    }


    public void start(){
        if (mMusicPlayer.isPlaying()){
            mMusicPlayer.pause();
            handler.removeCallbacks(runnable);
        }else{
            mMusicPlayer.start();
            handler.postDelayed(runnable, 0);
        }
        for(OnStateChangeListenr l : mListenerList) {
            l.onStateChange(mMusicPlayer.isPlaying(),mMusicPlayer.getCurrentPosition());
        }

    }

    public void prepareToPlay1(MusicItem item) {
        try {
            //重置播放器状态

            this.musicItem = item;

            handler.removeCallbacks(runnable);

            //设置播放音乐的地址
            mMusicPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            setDataSource();
        } catch (Exception e) {
            e.printStackTrace();
        }

        mMusicPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                for(OnStateChangeListenr l : mListenerList) {
                    l.loadfinised();
                }
            }
        });
        setmMusicPlayers();
    }

    public void prepareToPlay(MusicItem item) {
        try {
            //重置播放器状态

            handler.removeCallbacks(runnable);

            this.musicItem = item;


            mMusicPlayer.reset();
            //设置播放音乐的地址
            mMusicPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            setDataSource();
        } catch (Exception e) {
            e.printStackTrace();
        }
        mMusicPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {

                mediaPlayer.start();
                handler.postDelayed(runnable, 0);

                for(OnStateChangeListenr l : mListenerList) {
                    l.onPlay(mediaPlayer.getDuration());
                    l.onStateChange(mediaPlayer.isPlaying(),mediaPlayer.getCurrentPosition());
                }

            }
        });
        setmMusicPlayers();

    }
    public void setmMusicPlayers(){
        mMusicPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                if (playtype == 0){
                    if (musicItems.contains(musicItem)){
                        int i = musicItems.indexOf(musicItem);
                        if (i==musicItems.size()-1){
                            prepareToPlay(musicItems.get(0));
                        }else {
                            prepareToPlay(musicItems.get(i+1));
                        }
                    }
                }else if (playtype == 1){
                    prepareToPlay(musicItems.get(new Random().nextInt(musicItems.size()-1)));
                }else{
                    prepareToPlay(musicItem);
                }
                for(OnStateChangeListenr l : mListenerList) {
                    l.onPlayComplete();
                }
            }
        });

        mMusicPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
            @Override
            public void onSeekComplete(MediaPlayer mediaPlayer) {
                SystemClock.sleep(200);
                mediaPlayer.start();
            }
        });
    }


    public void setDataSource(){
            MyRetrofit.Down(super.getApplicationContext(), RetrofitService.class).getSong(musicItem.getId(),myApplication.getSetup().getPlaybr()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new MyObserver<getSongUrl>() {
                @Override
                public void onNext(@io.reactivex.rxjava3.annotations.NonNull getSongUrl getSongUrl) {
                    try {
                        if (getSongUrl!=null){
                            if (getSongUrl.getData()!=null){
                                setSql(musicItem);
                                mMusicPlayer.reset();
                                mMusicPlayer.setDataSource(getSongUrl.getData().get(0).getUrl());
                                //准备播放音乐
                                mMusicPlayer.prepareAsync();
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                    Toast.makeText(myApplication, "播放错误", Toast.LENGTH_SHORT).show();
                }

            });
    }

    public void onSchedule(long i){
        mMusicPlayer.seekTo((int) i);
        for(OnStateChangeListenr l : mListenerList) {
            l.onSchedule(i);
        }
    }


    public void next(){
        if (musicItems!=null){
            if (musicItems.contains(musicItem)){
                int i = musicItems.indexOf(musicItem);
                if (i>=musicItems.size()-1){
                    Toast.makeText(this, "到底了", Toast.LENGTH_SHORT).show();
                }else{
                    prepareToPlay(musicItems.get(i+1));
                }
            }
        }

    }

    public void back(){
        if (musicItems!=null){
            if (musicItems.contains(musicItem)){
                int i = musicItems.indexOf(musicItem);
                if (i<=0){
                    Toast.makeText(this, "前面没有了", Toast.LENGTH_SHORT).show();
                }else{
                    prepareToPlay(musicItems.get(i-1));
                }
            }
        }
    }

    public MediaPlayer getMusicPlayer(){
        return mMusicPlayer;
    }


    public interface OnStateChangeListenr {

        void onPlay(long time);//开始播放
        void onPlayComplete();//播放完成
        void onStateChange(boolean isplay,long nowtime);//播放状态改变
        void onSchedule(long nowtime);//划进度
        void OnTimeVariety(long nowtime);//时间变化
        void loadfinised();//播放准备好了
    }

    //创建存储监听器的列表
    private List<OnStateChangeListenr> mListenerList = new ArrayList<OnStateChangeListenr>();

    public void addOnStateChangeListenerInner(OnStateChangeListenr l) {
        //将监听器添加到列表
        mListenerList.add(l);
    }
    public void removeOnStateChangeListenerInner(OnStateChangeListenr l) {
        //将监听器从列表中移除
        mListenerList.remove(l);
    }

    Handler handler=new Handler();
    Runnable runnable=new Runnable(){
        @Override
        public void run() {
            for(OnStateChangeListenr l : mListenerList) {
                l.OnTimeVariety(mMusicPlayer.getCurrentPosition());
            }
            handler.postDelayed(this, 1000);
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_REDELIVER_INTENT;
    }
}
